import re
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from users.models import Address
from areas.models import Area
from oauth.models import OAuthQQUser
from users.models import User

#
class AreasSerialzier(serializers.ModelSerializer):

    class Meta:
        # 指定使用的模型类
        model = Area
        # 指定返回哪些数据内容
        fields = ("id","name")


class AddressSerializers(serializers.ModelSerializer):
    # 指定显示模型类中没有的字段
    # 这三个字段涉及到 关联嵌套序列化器的返回
    city = serializers.StringRelatedField(read_only=True)
    province = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    # 这三个字段数据不需要返回给前端
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)

    class Meta:
        # 指定序列化器使用的模型类
        model = Address
        # 指定序列化的字段
        fields = (
        'city_id', 'district_id', 'province_id', 'email', 'mobile', 'place', 'receiver', 'tel', 'title', 'city',
        'province', 'district','id')

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不匹配')

        return value

    def create(self, validated_data):
        # 通过context方法, 获取用户对象
        user = self.context['request'].user
        # 把用户对象添加到验证后的数据中
        validated_data['user'] = user
        # 赋值操作,将validated_data保存到模型类中
        address = Address.objects.create(**validated_data)

        return address



